#include "snetwork/NluConnection.h"

namespace Sock
{    
    CNluConnection *CNluConnection::m_instance = NULL;

    CNluConnection *CNluConnection::instance()
    {
        if (m_instance==NULL) {
            m_instance = new CNluConnection();
        }
        return m_instance;
    }    

	CNluConnection::CNluConnection()
	{
	
	}
	
	nlu_connection_t *CNluConnection::getConnection(nlu_cycle_t *cycle, int s)
    {
        u_int             instance;
        nlu_event_t       *rev, *wev;
        nlu_connection_t  *c;

        /* ngx_mutex_lock */

        c = cycle->free_connections;

        if (c == NULL) {
            llog("%ui worker_connections are not enough",
                          cycle->connection_n);

            /* ngx_mutex_unlock */

            return NULL;
        }

        cycle->free_connections = c->data;
        cycle->free_connection_n--;

        rev = c->read;
        wev = c->write;

        memset(c, 0, sizeof(nlu_connection_t));

        c->read = rev;
        c->write = wev;
        c->fd = s;

        instance = rev->instance;

        memset(rev, 0, sizeof(nlu_event_t));
        memset(wev, 0, sizeof(nlu_event_t));

        rev->instance = !instance;
        wev->instance = !instance;

        rev->data = c;
        wev->data = c;

        wev->write = 1;

        return c;
    }
    
    void CNluConnection::freeConnection(nlu_cycle_t *cycle, nlu_connection_t *c)
    {
        /* ngx_mutex_lock */

        c->data = ngx_cycle->free_connections;
        cycle->free_connections = c;
        cycle->free_connection_n++;

        /* ngx_mutex_unlock */

        if (cycle->files) {
            cycle->files[c->fd] = NULL;
        }
    }
	
    int CNluConnection::execute(void* pa)    
    {        
        return 0;
    }   
}



	
